import wx from '../../../subwe/bridge';
import WXPage from "../../../subwe/page";
import { Index } from '../../../apis/index';
const app = getApp();
const API = new Index();
WXPage({
  data: {
    goodsList: [],
    imageUrl: `${app.globalData.imageUrl}/zhongman2`,
    room: "",
    placeId: "",
    loginInfo: wx.getStorageSync('login_key'),
    deviceInfo: {},
    totalPrice: 0,
    discountAmount: 0,
    host: "",
    payLoading: false
  },
  onLoad(options) {
    this.getroomNum();
  },
  // 获取房间号和设备号
  getroomNum() {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    API.getDeviceInfo({
      deviceSn: app.globalData.deviceSn
    }).then(res => {
      wx.hideLoading();
      this.setData({
        deviceInfo: res.result
      });
      this.getCartInfo();
    }, () => {
      wx.hideLoading();
    });
  },
  // 获取购物车列表信息
  getCartInfo() {
    API.getCartList({
      placeId: this.data.deviceInfo.placeId
    }).then(res => {
      const {
        data,
        host
      } = res.result;
      let totalPrice = 0;
      let discountAmount = 0;
      const arr = data.map(i => {
        discountAmount += i.buyNum * i.discountAmount / 100;
        return i.buyNum * i.price / 100;
      });
      if (arr && arr.length > 0) {
        totalPrice = arr.reduce((prev, curr, idx, arr) => {
          return prev + curr;
        });
      }
      this.setData({
        goodsList: data,
        discountAmount: discountAmount,
        totalPrice: (totalPrice - discountAmount).toFixed(2),
        host
      });
    });
  },
  bindTextAreaBlur(e) {
    this.setData({
      message: e.detail.value
    });
  },
  // 确认支付 获取支付信息
  confirmPay() {
    if(this.data.payLoading) return
    this.setData({payLoading: true})
    setTimeout(ev => this.setData({payLoading: false}), 5000)

    const {
      deviceInfo,
      loginInfo,
      message,
      goodsList
    } = this.data;
    const list = goodsList.map(i => {
      return {
        num: i.buyNum,
        id: i.goodsId
      };
    });
    API.createGoodsOrder({
      deviceSn: app.globalData.deviceSn,
      placeId: deviceInfo.placeId,
      openid: loginInfo.openid,
      goodsList: list,
      message
    }).then(res => {
      API.clearCart({
        // 清空购物车
        placeId: this.data.deviceInfo.placeId
      });
      this.wxPayment(res.result.pay);
    });
  },
  // 微信支付
  wxPayment(data) {
    const {
      placeId,
      ruleInfo
    } = this.data.deviceInfo;
    if (!placeId || !ruleInfo || !ruleInfo.length) {
      wx.showModal({
        title: '提示',
        content: "设备未绑定使用，请联系工作人员",
        showCancel: false
      });
      return;
    }

    let { out_trade_no, trade_no } = data.AliPayTradeCreateResBody || {}
    my.tradePay({
      tradeNO: out_trade_no,
      success: (res) => {
        wx.hideLoading();
        console.log("wxPayment-success", res);
        if(Number(res.resultCode) === 9000) {
          setTimeout(() => {
            wx.reLaunch({url: `/pages/supermarket/submitSuccess/submitSuccess?tradeNo=${trade_no}`});
          }, 1000);
          return
        }
        wx.showToast({title: res.memo || '支付失败', icon: 'none'})
        setTimeout(() => {
          wx.reLaunch({url: `/pages/supermarket/supermarketOrder/supermarketOrder`});
        }, 800);
      },
      fail: (res) => {
        wx.hideLoading()
        console.log("fail info", res);
        wx.showToast({
          title: '支付中断',
          icon: 'none'
        });
      }
    });

    // const param = JSON.parse(data);
    // wx.requestPayment({
    //   timeStamp: param.timeStamp,
    //   nonceStr: param.nonceStr,
    //   package: param.package,
    //   signType: param.signType,
    //   paySign: param.paySign,
    //   success() {
    //     setTimeout(() => {
    //       wx.reLaunch({
    //         url: `/pages/supermarket/submitSuccess/submitSuccess?tradeNo=${param.tradeNo}`
    //       });
    //     }, 1000);
    //   },
    //   fail(res) {
    //     wx.reLaunch({
    //       url: `/pages/supermarket/supermarketOrder/supermarketOrder`
    //     });
    //     console.log("fail info", res);
    //   }
    // });
  }
});
